package com.atomscat.lottery.service;

import com.atomscat.lottery.entity.db.LotteryRecordEntity;
import com.atomscat.lottery.entity.db.LotteryUserRecordEntity;
import com.atomscat.lottery.entity.vo.request.PageLotteryRecordRequest;
import com.atomscat.lottery.repository.LotteryRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class LotteryRecordService {
    private final LotteryRecordRepository lotteryRecordRepository;

    public LotteryRecordEntity createLotteryRecord(Long activityId, Long userId, Long prizeId) {
        LotteryRecordEntity lotteryRecordEntity = new LotteryRecordEntity();
        lotteryRecordEntity.setLotteryState("Unclaimed");
        lotteryRecordEntity.setActivityId(activityId);
        lotteryRecordEntity.setPrizeId(prizeId);
        lotteryRecordEntity.setUserId(userId);
        return lotteryRecordRepository.saveAndFlush(lotteryRecordEntity);
    }


    public Page<LotteryRecordEntity> pageLotteryRecordEntity(PageLotteryRecordRequest pageLotteryRecordRequest) {
        PageRequest pageable = PageRequest.of(pageLotteryRecordRequest.getPageNumber(), pageLotteryRecordRequest.getPageSize());
        LotteryRecordEntity lotteryRecordEntity = new LotteryRecordEntity();
        return lotteryRecordRepository.findAll(Example.of(lotteryRecordEntity), pageable);
    }

    public Page<LotteryUserRecordEntity> pageLotteryUserRecord(PageLotteryRecordRequest pageLotteryRecordRequest) {
        PageRequest pageable = PageRequest.of(pageLotteryRecordRequest.getPageNumber(), pageLotteryRecordRequest.getPageSize());
        if (pageLotteryRecordRequest.getActivityId() != null && pageLotteryRecordRequest.getPrizeId() != null) {
            return lotteryRecordRepository.findByActivityId(pageLotteryRecordRequest.getActivityId(), pageLotteryRecordRequest.getPrizeId(), pageable);
        }
        return lotteryRecordRepository.findByActivityId(pageLotteryRecordRequest.getActivityId(), pageable);
    }

}
